package com.haibei.activity.consult;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.sharesdk.BaiduShareException;
import com.baidu.sharesdk.BaiduSocialShare;
import com.baidu.sharesdk.ShareContent;
import com.baidu.sharesdk.ShareListener;
import com.baidu.sharesdk.SocialShareLogger;
import com.baidu.sharesdk.Utility;
import com.baidu.sharesdk.ui.BaiduSocialShareUserInterface;
import com.common.net.NetResult;
import com.common.task.BaseTask;
import com.common.task.NetCallBack;
import com.common.uitl.DateTool;
import com.common.uitl.ListUtiles;
import com.common.uitl.StringUtils;
import com.common.uitl.Tool;
import com.haibei.App;
import com.haibei.BaiduSocialShareConfig;
import com.haibei.R;
import com.haibei.activity.BaseHaibeiActivity;
import com.haibei.activity.common.CommentActivity;
import com.haibei.activity.user.LoginActivity;
import com.haibei.adapter.ArticleContentAdapter;
import com.haibei.adapter.bean.Article;
import com.haibei.adapter.bean.Comment;
import com.haibei.adapter.bean.ContentItem;
import com.haibei.adapter.bean.User;
import com.haibei.net.NetInterface;

public class ConsultDetailActivity extends BaseHaibeiActivity {

	private Button butonShare;
	private BaseTask mBaseTask;
	private BaiduSocialShare socialShare;
	private Button buttonComment;
	private Button buttonCollect;
	private ListView listViewContent;
	private BaiduSocialShareUserInterface socialShareUi;
	private ShareContent pageContent;
	private final static String appKey = BaiduSocialShareConfig.mbApiKey;
	private final static String wxAppId = BaiduSocialShareConfig.appID;
	final Handler handler = new Handler(Looper.getMainLooper());
	private TextView textViewComment;
	private LinearLayout mlinearLayoutFooter;
	public static ArrayList<Comment> hotelCommentList;
	private Article mArticle;
	private View headerView;
	private final int INT_GO_COMMENT = 100;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mArticle = (Article) getIntent().getSerializableExtra("article");
		shareInit();
		initView();
	}

	private void shareInit() {
		socialShare = BaiduSocialShare.getInstance(this, appKey);
		socialShareUi = socialShare.getSocialShareUserInterfaceInstance();
		// 实例化baidu社会化分享，传入appkey
		// 设置支持微信平台 传入wxAppId
		socialShare.supportWeixin(wxAppId);
		// 设置支持腾讯微博单点登录的appid
		socialShare.supportQQSso(BaiduSocialShareConfig.QQ_SSO_APP_KEY);
		// 设置支持新浪微博单点登录的appid
		socialShare.supportWeiBoSso(BaiduSocialShareConfig.SINA_SSO_APP_KEY);
		// 获取社会化分享UI的实例对象 当自定义UI时使用
		socialShareUi = socialShare.getSocialShareUserInterfaceInstance();
		SocialShareLogger.on();

		pageContent = new ShareContent();
		pageContent.setContent("海贝，不错的母婴应用....");
		pageContent.setTitle("百度开发中心");
		pageContent.setUrl("http://developer.baidu.com");
		pageContent.setImageUrl("http://apps.bdimg.com/developer/static/04171450/developer/images/icon/terminal_adapter.png");

	}

	// 分享网页 使用主题风格的样式菜单
	public void page_share_theme_style() {
		socialShareUi.showShareMenu(this, pageContent, Utility.SHARE_THEME_STYLE, new ShareListener() {
			@Override
			public void onAuthComplete(Bundle values) {
			}

			@Override
			public void onApiComplete(String responses) {
				final String msg = responses;
				handler.post(new Runnable() {
					@Override
					public void run() {
						Utility.showAlert(ConsultDetailActivity.this, msg);
					}
				});
			}

			@Override
			public void onError(BaiduShareException e) {

			}

		});
	}

	@Override
	public void initView() {
		setContentView(R.layout.activity_consult_detail);
		textViewComment = findTextViewById(R.id.textViewComment);
		textViewComment.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent();
				i.setClass(ConsultDetailActivity.this, CommentActivity.class);
				startActivityForResult(i, INT_GO_COMMENT);
			}
		});
		listViewContent = findListViewById(R.id.listViewContent);
		buttonComment = findButtonById(R.id.buttonCommentCount);
		buttonComment.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				gotoComments();
			}
		});
		buttonCollect = findButtonById(R.id.buttonCollect);
		buttonCollect.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (App.isLogin()) {
					HashMap<String, String> hmap = new HashMap<String, String>();
					hmap.put("uid", App.getApp().getUser().getUid());
					hmap.put("articleId", mArticle.getId());
					getCollectTask().execute(hmap);
				} else {
					Tool.startActivity(ConsultDetailActivity.this, LoginActivity.class);
				}
			}
		});
		butonShare = findButtonById(R.id.buttonShare);
		butonShare.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				page_share_theme_style();
			}
		});

		mlinearLayoutFooter = (LinearLayout) View.inflate(this, R.layout.footerview_article_conent, null);
		findButtonById(R.id.buttonBack).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		initStaticContent();
		requestArticleDetail();
	}

	private void requestArticleDetail() {
		if (null != mArticle) {
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("articleId", mArticle.getId());
			getBaseTaskComments().execute(map);
		}
	}

	private View createHeaderView() {
		headerView = View.inflate(this, R.layout.header_consult, null);
		return headerView;
	}
	//初始化相关内容
	private void initStaticContent() {
		if (null != mArticle) {

			View headerView = createHeaderView();

			TextView textViewTitle = (TextView) headerView.findViewById(R.id.textViewConsultTitle);
			TextView textViewAuthorAndAuthor = (TextView) headerView.findViewById(R.id.textViewAuthorAndAuthor);
			TextView textViewDate = (TextView) headerView.findViewById(R.id.textViewDate);

			textViewTitle.setText("    " + mArticle.getTitle());
			long time = Long.parseLong(mArticle.getPublishTime());
			textViewAuthorAndAuthor.setText(mArticle.getOrigin() + "   " + mArticle.getAuthor());
			textViewDate.setText(DateTool.getLongTime4Ymdhms(time));

			listViewContent.addHeaderView(headerView);
			ArrayList<ContentItem> list = mArticle.getContentList();
			ArticleContentAdapter aca = new ArticleContentAdapter(this, list);

			listViewContent.addFooterView(mlinearLayoutFooter);

			Button btn = (Button) View.inflate(this, R.layout.button_view, null);
			btn.setText("查看原文");
			LinearLayout.LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
			int marginDimen = (int) getResources().getDimension(R.dimen.pading_content);
			lp.setMargins(0, marginDimen, 0, marginDimen);
			btn.setTextColor(getResources().getColor(R.color.text_color_dark));
			mlinearLayoutFooter.addView(btn, lp);
			ImageView spliteh = new ImageView(this);
			spliteh.setBackgroundResource(R.drawable.bg_split_h);
			mlinearLayoutFooter.addView(spliteh);

			listViewContent.setAdapter(aca);

		}
	}

	// private void addContentView(ArrayList<ContentItem> list) {
	// for (int i = 0, isize = list.size(); i < isize; i++) {
	// ContentItem ic = list.get(i);
	// if (ic.isImg()) {
	// View imgView = View.inflate(this, R.layout.item_detail_article_img,
	// null);
	// com.haibei.view.BackAsnycImageView byasync = (BackAsnycImageView)
	// imgView.findViewById(R.id.imageViewPic);
	// String url = ic.getContent();
	// byasync.setUrl(url);
	// linearLayoutContent.addView(imgView);
	// } else {
	// View textView = View.inflate(this, R.layout.item_detail_article_text,
	// null);
	// String content = ic.getContent().replace(" ", "");
	// content = ic.getContent().replace("\r", "\n");
	// ((TextView) textView.findViewById(R.id.textViewText)).setText("    " +
	// content);
	//
	// linearLayoutContent.addView(textView);
	// }
	// }
	//
	// Button btn = (Button) View.inflate(this, R.layout.button_view, null);
	// btn.setText("查看原文");
	// LinearLayout.LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT,
	// LayoutParams.WRAP_CONTENT);
	// int marginDimen = (int)
	// getResources().getDimension(R.dimen.pading_content);
	// lp.setMargins(0, marginDimen, 0, marginDimen);
	// btn.setTextColor(getResources().getColor(R.color.text_color_dark));
	// linearLayoutContent.addView(btn, lp);
	// ImageView spliteh = new ImageView(this);
	// spliteh.setBackgroundResource(R.drawable.bg_split_h);
	// linearLayoutContent.addView(spliteh);
	// }

	/**
	 * 添加热门评论
	 * 
	 * @param hotsComments
	 * @param commentCount
	 */
	private void addComments(ArrayList<Comment> hotsComments, String commentCount) {
		if (!ListUtiles.isEmpty(hotsComments)) {
			mlinearLayoutFooter.addView(View.inflate(this, R.layout.item_comments_divider, null));
		}
		for (int i = 0, isize = hotsComments.size(); i < isize; i++) {
			ImageView spliteh = new ImageView(this);
			spliteh.setBackgroundResource(R.drawable.bg_split_h);
			mlinearLayoutFooter.addView(spliteh);

			Comment comment = hotsComments.get(i);
			View commentItem = View.inflate(this, R.layout.item_article_comments, null);
			com.haibei.view.AsnycImageView headerImg = (com.haibei.view.AsnycImageView) commentItem.findViewById(R.id.asImageHeader);// 头像
			headerImg.setUrl(comment.getUser().getHeadPortrait());

			TextView textViewAuthor = (TextView) commentItem.findViewById(R.id.textViewAuthor);// 标题
			textViewAuthor.setText(comment.getUser().getNikename());

			TextView textTime = (TextView) commentItem.findViewById(R.id.textTime);// 时间

			// =========
			SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");

			Calendar ca = Calendar.getInstance();
			ca.setTimeInMillis(Long.parseLong(comment.getTime()));
			textTime.setText(sdf.format(ca.getTime()));
			TextView textViewGood = (TextView) commentItem.findViewById(R.id.textViewGood);// 赞
			textViewGood.setText("赞" + comment.getPraise());
			TextView content = (TextView) commentItem.findViewById(R.id.textViewComment);
			content.setText(comment.getContent());

			mlinearLayoutFooter.addView(commentItem);
		}

		// 查看评论
		if (!ListUtiles.isEmpty(hotsComments)) {
			ImageView spliteh = new ImageView(this);
			spliteh.setBackgroundResource(R.drawable.bg_split_h);
			mlinearLayoutFooter.addView(spliteh);
		}
		Button btn = (Button) View.inflate(this, R.layout.button_view, null);
		btn.setText("查看全部评论");
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				gotoComments();
			}
		});
		LinearLayout.LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		int marginDimen = (int) getResources().getDimension(R.dimen.pading_content);
		lp.setMargins(0, marginDimen, 0, marginDimen);
		btn.setTextColor(getResources().getColor(R.color.text_color_blue));
		mlinearLayoutFooter.addView(btn, lp);
		// }
		// 评论条数
		Button btnCount = findButtonById(R.id.buttonCommentCount);
		btnCount.setText(commentCount);
	}

	private void gotoComments() {
		Intent i = new Intent();
		i.putExtra("article", mArticle);
		i.setClass(ConsultDetailActivity.this, ArticleCommentsActivity.class);
		startActivity(i);
	}

	/**
	 * 评论
	 */
	private void comment(String comment) {
		HashMap<String, String> hmap = new HashMap<String, String>();
		// uid, articleId, commentContent
		User u = App.getApp().getUser();
		if (null != u) {
			hmap.put("uid", u.getUid());
			hmap.put("articleId", mArticle.getId());
			hmap.put("commentContent", comment);
			getCommentTask().execute(hmap);
		} else {
			Tool.ToastShow(ConsultDetailActivity.this, "请先登录!");
			Tool.startActivity(ConsultDetailActivity.this, LoginActivity.class);
		}
	}

	private void clearComments() {

		findEditTextById(R.id.editTextComment).setText("");

	}

	private BaseTask getCommentTask() {
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		mBaseTask = new BaseTask(new NetCallBack() {

			@Override
			public void onPreCall() {
				showProgressDialogWithTask(mBaseTask);
			}

			@Override
			public void onFinish(NetResult result) {
				hideProgressDialogWithTask();
				if (null != result) {
					if (result.isSuccess()) {
						clearComments();
						Tool.ToastShow(ConsultDetailActivity.this, "评论成功！");
						Tool.startActivity(ConsultDetailActivity.this, ArticleCommentsActivity.class);
					} else {
						Tool.ToastShow(ConsultDetailActivity.this, result.getMessage());
					}
				} else {
					Tool.ToastShow(ConsultDetailActivity.this, R.string.error_net);
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult netResult = null;
				try {
					netResult = NetInterface.addComment(ConsultDetailActivity.this, paramMap);
				} catch (Exception e) {
				}
				return netResult;
			}
		});
		return mBaseTask;
	}

	/**
	 * 获取评论
	 * 
	 * @return
	 */
	private BaseTask getBaseTaskComments() {
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		mBaseTask = new BaseTask(new NetCallBack() {
			@Override
			public void onPreCall() {
				showProgressDialogWithTask(mBaseTask);
			}

			@Override
			public void onFinish(NetResult result) {
				hideProgressDialogWithTask();
				if (null != result) {
					String commentCount = (String) result.getData()[0];
					hotelCommentList = (ArrayList<Comment>) result.getData()[1];
					addComments(hotelCommentList, commentCount);
				} else {
					Tool.ToastShow(ConsultDetailActivity.this, R.string.error_net);
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult netResult = null;
				try {
					netResult = NetInterface.getArticleDetail(ConsultDetailActivity.this, paramMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return netResult;
			}
		});
		return mBaseTask;
	}

	private BaseTask getCollectTask() {
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		mBaseTask = new BaseTask(new NetCallBack() {

			@Override
			public void onPreCall() {
				showProgressDialogWithTask(mBaseTask);
			}

			@Override
			public void onFinish(NetResult result) {
				hideProgressDialogWithTask();
				if (null != result) {
					if (result.isSuccess()) {
						Tool.ToastShow(ConsultDetailActivity.this, "收藏成功");
					} else {
						Tool.ToastShow(ConsultDetailActivity.this, result.getMessage());
					}
				} else {
					Tool.ToastShow(ConsultDetailActivity.this, R.string.error_net);
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult netResult = null;
				try {
					netResult = NetInterface.collectArticle(ConsultDetailActivity.this, paramMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return netResult;
			}
		});
		return mBaseTask;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (INT_GO_COMMENT == requestCode) {
			if (RESULT_OK == resultCode) {
				String comment = data.getStringExtra("data");
				if (!StringUtils.isEmpty(comment)) {
					comment(comment);
				}
			}
		}
	}
}
